// pages/car/message/driverDetails/driverDetails.js
// var cityData = require('../../../../utils/citydata.js');
const app =getApp();
Page({

    data: {
        img:"",//头像
        name:'', // 姓名
        phone: '', // 电话
        plate: '', //车牌号
        show: false, // 车型弹出层
        longList:[], // 车长数组
        longId:null, // 车长索引
        modelList:[], // 车型
        modelId: null, // 车型索引
        longName:'', // 车长名字
        carLonglId: '',// 车长id
        modelName:'',   // 车型名字
        carModellId:'', // 车型id
        newsId:0, // 车型点击改变状态
        LongModelId:'', // 车长车型id
        VehicleId:'',// 车长
        VehicleMOdelId: '',// 车型
        selectActive: false, // 选中自定义车型
        valuedd:'', // 自定义车型
        newsList:[], // 资讯列表
        showLoad: false, // 装卸货地弹出层
        type: '',// 判断点击哪个省市区
        province_zid: '北京市', // 装货省
        city_zid: '北京市辖区', // 装货市
        area_zid: '东城区', // 装货区
        installInput: '', //装货地详细地址
        regionTwo: '',
        installColor: '#999', // 装货地颜色
        installSize:'22rpx', // 装货地字体大小
        installBold: '400', // 装货地字体加粗
        province_xid: '北京市', // 卸货省
        city_xid: '北京市辖区', // 卸货市
        area_xid: '东城区', // 卸货区
        removeInput: '', //卸货地详细地址
        regionThree: "",
        removeColor: '#999', //卸货地颜色
        removeSize: '22rpx', // 卸货地字体大小
        removeBold: '400', // 卸货地字体加粗
        citysData: [],
        provinces: [],
        citys: [],
        areas: [],
        value: [0,0,0],     
        showFour: false,// 发车时间弹出层
        regionFour: [],// 发车时间显示
        currentDate: new Date().getTime(),
        // minDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          } else if (type === 'day') {
            return `${value}日`;
          }
          return value;
        },
    },
    onLoad: function (options) {
        wx.showLoading({
            title:'加载中···'
        })
        this.setData({
            img : wx.getStorageSync('headImg')
        })
        this.getPlace(); // 筛选地区
        this.getCarType();// 车型
        this.getCarLong(); // 车长
        this.initData(); //省市区 
        this.ownerdata();
        console.log(wx.getStorageSync('headImg'),'头像子')
    },
    // 姓名
    inputName(event){
        this.setData({
            name: event.detail.value
        })
    },
    // 电话
    inputNumber(event){
        this.setData({
            phone: event.detail.value
        })
    },
    // 车牌号
    inputPlate(event){
        this.setData({
            plate: event.detail.value
        })
    },
    //车型 显示
    showPopup() {
        this.setData({ 
            show: true,
        });
    },
    // 关闭
    onClose() {
        this.setData({ show: false });
    },
    // 确认
    onConfirm(event) {
        // console.log(event,222)
        const { picker, value, index } = event.detail;
        if( this.data.longName == '' ){
            wx.showToast({
              title: '请选择车长',
              icon: 'none'
            })
            return false
        } else if( this.data.modelName == ''&& this.data.valuedd == ''){
            wx.showToast({
                title: '请选择车型',
                icon: 'none'
            })
            return false
        } else {
            if(this.data.selectActive == true){
                // 自定义车型
                var values = this.data.longName+'米' +'/' + this.data.valuedd
            } else {
                // 车型
                var values =this.data.longName+'米' +'/' + this.data.modelName;
            }
        }
        this.setData({
            show: false,
            region: values,
            LongModelId : this.data.carLonglId + ' ' + this.data.carModellId,
            VehicleId: this.data.carLonglId ,
            VehicleMOdelId:this.data.carModellId,
        });
        // console.log(this.data.value)
    },
    // 取消
    onCancel() {
        console.log('取消');
        this.setData({ 
            show: false,
            selectActive: false,
            value: '',
            longId: null,
            modelId: null, 
            valuedd: ''
        });
    },
    // 车长点击
    modelClick(event){
        // console.log(event)
        var index = event.currentTarget.dataset.index;
        var name = event.currentTarget.dataset.name;
        var id = event.currentTarget.dataset.id;
        // console.log(id)
        this.setData({
          longId : index,
          longName : name,
          carLonglId: id
        })
    },
    // 车型点击
    modelClickTwo(event){
        var index = event.currentTarget.dataset.index; // 车型索引   
        var name = event.currentTarget.dataset.name;
        var id = event.currentTarget.dataset.id;
        this.setData({
            modelId : index,
            modelName: name,
            carModellId: id,
            selectActive: false,
            value: ''
        })
    },
    // 自定义车型
    // selectInput(event){
    //     console.log(event,876)
    //     this.setData({
    //         valuedd: event.detail.value,
    //         colorSize:'#000',
    //     })
    // },
    // 获取焦点
    // focus(){
    //     console.log(this.data.carModellId,777)
    //     this.setData({
    //         index: null,
    //         modelId: null,
    //         selectActive: true,
    //         carModellId: ''// 车型id
    //     })
    // },
    // 车型
    getCarType(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/getcar',
            method: 'GET',
            data:{
            },
            success: res => {
            //   console.log(res,99988)
              this.setData({
                modelList: res.data.data
              })
            //   console.log(this.data.modelList)
            },
            fail: err => {
              console.log(err)
            },
            complete: () => {
              wx.hideLoading()
            }
        })  
    },
    // 车长
    getCarLong(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/conductor',
            method: 'GET',
            data:{},
            success: res => {
                // console.log(res,989)
                this.setData({
                    longList: res.data.data
                })
            },
            fail: err => {
              console.log(err)
            },
            complete: () => {
              wx.hideLoading()
            }
        })  
    },
    // 装卸货地
    initData: function(){
        var provinces = [];
        var citys = [];
        var areas = [];
        this.data.citysData.forEach(function(province,i){
            provinces.push(province.name);
            if(i===0){
                citys.push(province.citys[i].name);
                areas = province.citys[i].areas;
            }
        });    
        this.setData({
            provinces: provinces,
            citys: citys,
            areas: areas
        });
    },
    // 装卸货地
    bindChange: function(e){
        // console.log(e)
        var citysData = this.data.citysData;
        var value = this.data.value;
        var current_value = e.detail.value;
        var citys = [];   
        var provinceObj = {};
        var cityObj = {};   
        provinceObj = citysData[current_value[0]];
    
        if (value[0] !== current_value[0]) {
            // 滑动省份
            provinceObj.citys.forEach(function(v){
                citys.push(v.name);
            });
            this.setData({
                citys: citys
            });
    
            cityObj = provinceObj.citys[0];
            this.setData({
                areas: cityObj.areas,
                value: [current_value[0],0,0]
            });
    
        }else if(value[0] === current_value[0] && value[1] !== current_value[1]){
            // 滑动城市
            if(current_value[1]>=provinceObj.citys.length){
                // 数据不存在 跳过
                return;
            }
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                areas: cityObj.areas,
                value: [current_value[0],current_value[1],0]
            });
        }else{
            // 滑动区县
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                value: current_value
            });
        }
        if(this.data.type == 0) {
            this.setData({
                province_zid: provinceObj.name,
                city_zid: cityObj.name,
                area_zid: cityObj.areas[this.data.value[2]],
            });
        }else{
            this.setData({
                province_xid: provinceObj.name,
                city_xid: cityObj.name,
                area_xid: cityObj.areas[this.data.value[2]]
            })
        }
    },
    //显示装卸货地
    showLoad(e) {
        console.log(e)
        this.setData({
            type: e.currentTarget.dataset.type,
            showLoad: true,
        })
    },
    // 关闭装卸货地
    onCloses(){
        this.setData({
            showLoad: false
        })
    },
    //取消装卸货地
    loadCancel() {
        this.setData({
            showLoad: false
        })
    },
    //装卸货地确定按钮
    loadConfirm() {
        if(this.data.type == 0) {
            this.setData({
                showLoad: false,
                regionTwo: this.data.province_zid+' '+this.data.city_zid+' '+this.data.area_zid,
                page: 1,
                installColor: "#333",
                installSize: '26rpx',
                installBold: '700',
            })
        }else{
            this.setData({
                showLoad: false,
                regionThree: this.data.province_xid+' '+this.data.city_xid+' '+this.data.area_xid,
                page: 1,
                removeColor: '#333',
                removeSize: '26rpx',
                removeBold: '700',
            })
        }
    },
    // 发车时间
    onInput(event) {
        this.setData({
          currentDate: event.detail,
        });
    },
    // 显示
    showPopupFour(){
        this.setData({ showFour: true });
    },
     // 关闭
    onCloseFour() {
        this.setData({ showFour: false });
    },
     // 确认
    onConfirmFour(event) {
        // console.log(event.detail,99999)
        if(event.detail == ""){
            return ;
        }
        var date = this.getDate(event.detail);
        var arr = date.split(" ");
        var time = arr[0].split("-")
        const { picker, value, index } = event.detail;
        this.setData({ 
            showFour: false,
            regionFour: event.detail,
        });
        let year = time[0]; 
        var month = time[1];
        var day = time[2];
        if(month<10){ 
            month = '0'+month 
        }
        if( parseInt(day)<10){
            day = '0'+day  
        }
        this.setData({
            regionFour:  year + '-' + month + '-' +  day
        })
    },
    // 取消
    onCancelFour(){
        console.log('取消1');
        this.setData({ showFour: false });
    },
    // 改变
    onChangeFour(event) {
        const { picker, value, index } = event.detail;
        console.log(`当前值：${value}, 当前索引：${index}`);
    },
     // 获取信息 姓名电话手机号
     ownerdata(){
        wx.showLoading({
          title: '加载中···',
        })
        wx.request({
          url: app.globalData.url + 'api/v1/owner/login/ownerdata',
          method: 'GET',
          data:{
            id: wx.getStorageSync('id')
          },
          success: res => {
            // console.log(res);
            this.setData({
              name: res.data.data.name,
              phone: res.data.data.phone,
              plate: res.data.data.plate
            })
          },
          fail: err => {
            console.log(err)
          },
          complete: () => {
            wx.hideLoading()
          }
        })   
    },
    // 地区
    getPlace(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/region',
            method: 'get',
            data:{},
            success: res => {
                // console.log(res.data.data,999)
                this.setData({
                    citysData: res.data.data
                })
                this.initData(); // 装货地省市区 
                this.initDatas(); // 卸货地省市区
            },
            fail: err => {
              console.log(err)
            },
        })
    }, 
    // 发布
    submit(){
        if(this.data.name==''){
            wx.showToast({
                title: '请输入你的真实姓名',
                icon: 'none',
            })
            return false
        } else if ( !/^[\u4e00-\u9fa5]{0,16}$/.test(this.data.name) ){
            wx.showToast({
              title: '请正确输入您的姓名',
              icon: 'none',
            })
            return false
        }  else if(this.data.phone == ''){
            wx.showToast({
                title: '请输入您的电话号码',
                icon: 'none',
            })
            return false
        } else if (!/^1[3456789]\d{9}$/.test(this.data.phone) ){
            wx.showToast({
              title: '手机号格式不正确',
              icon: 'none',
            })
            return false
        } else if(this.data.plate == ''){
            wx.showToast({
                title: '请输入您的车牌号',
                icon: 'none',
            })
            return false
        } else if(!/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[警京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/.test( this.data.plate)){
            wx.showToast({
              title: "请输入正确的车牌号",
              icon: "none",
            })
            return false
          } else if(this.data.region == null){
            wx.showToast({
                title: '请选择您的车型',
                icon: 'none',
            })
            return false
        } else if(this.data.regionTwo == '' ){
            wx.showToast({
                title: '请选择您的装车地',
                icon: 'none',
            })
            return false
        } else if(this.data.regionThree == '' ){
            wx.showToast({
                title: '请选择您的卸车地',
                icon: 'none',
            })
            return false
        } else if(this.data.regionFour == '' ){
            wx.showToast({
                title: '请选择您的发车时间',
                icon: 'none',
            })
            return false
        }
        wx.request({
            url: app.globalData.url + 'api/v1/owner/owner/resources',
            method: 'POST',
            data:{
                owner_id: wx.getStorageSync('id'),
                img: this.data.img,
                name: this.data.name,
                phone: this.data.phone,
                plate: this.data.plate,
                conductor_id:this.data.VehicleId, // 车长
                cartype: this.data.VehicleMOdelId, // 车型
                custom: this.data.valuedd, // 自定义车型
                province_zid: this.data.province_zid,
                city_zid: this.data.city_zid,
                area_zid: this.data.area_zid,
                province_xid: this.data.province_xid,
                city_xid: this.data.city_xid,
                area_xid: this.data.area_xid,
                // province_zid: ,
                // city_zid: ,
                // area_zid: ,
                // province_xid: ,
                // city_xid: ,
                // area_xid: ,
                time: this.data.regionFour
            },
            success: res => {
                // console.log(res,999)
                if (res.data.code == 200){
                    setTimeout(() => {
                        wx.showToast({
                            title: '发布成功',
                            icon: 'none',
                        })
                    },500)
                    setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                    },1000)
                } else{
                    wx.showToast({
                        title: '发布失败',
                        icon: 'none',
                    })
                }
            },
            fail: err => {
                console.log(err)
            },
            complete: () => {
                wx.hideLoading()
            }
        }) 
    },
     // 时间戳
    getDate(unixtime) {
        var dateTime = new Date(parseInt(unixtime))
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        // var hour = dateTime.getHours();
        // var minute = dateTime.getMinutes();
        // var second = dateTime.getSeconds();
        var now = new Date();
        var now_new = Date.parse(now.toDateString()); //typescript转换写法
        var milliseconds = now_new - dateTime;
        var timeSpanStr = year + '-' + month + '-' + day 
        return timeSpanStr;
    },
        /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }  
})